﻿<%@ WebHandler Language="C#" Class="ResCalendarWorkShiftMaintHandler" %>

/*Description: 设备日历班次维护处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20250813
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Text;

public class ResCalendarWorkShiftMaintHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetResourceList": //获取设备列表
                    GetResourceList(context);
                    break;
                case "GetResourceCalDetail": //获取设备日历班次明细
                    GetResourceCalDetail(context);
                    break;
                case "GetWorkShiftListByDate": //获取该日期的班次明细
                    GetWorkShiftListByDate(context);
                    break;
                case "SaveResCalWorkShiftData": //保存设备日历班次数据
                    SaveResCalWorkShiftData(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知操作" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 获取设备列表
    /// </summary>
    /// <param name="context"></param>
    public void GetResourceList(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "获取成功" };
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());//查询参数
        if (string.IsNullOrWhiteSpace(dic["StartDate"]) || string.IsNullOrWhiteSpace(dic["EndDate"]))
        {
            result.Result = false;
            result.Message = "请选择日期范围！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        /*查询数据*/
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT r.resourcename,r.resourceid,r.description resourcedesc,
                            wc.workcentername,t.teamname,mc.makecalendarname,ws.workshiftname,ws.workshiftid
                            FROM Resourcedef r 
                            LEFT JOIN workcenter wc ON wc.workcenterid = r.workcenterid
                            LEFT JOIN team t ON t.teamid = r.teamid
                            LEFT JOIN makecalendar mc ON mc.makecalendarid = r.makecalendarid
                            LEFT JOIN workshift ws ON ws.workshiftid = r.workshiftid
                            WHERE r.factoryid = '{0}' AND r.isuse = 0", m_UserInfo.FactoryID);
        if (dic.ContainsKey("ResourceName") && !string.IsNullOrWhiteSpace(dic["ResourceName"]))
        {
            sql.AppendFormat(" AND r.resourcename = '{0}'", dic["ResourceName"]);
        }
        if (dic.ContainsKey("WorkCenterName") && !string.IsNullOrWhiteSpace(dic["WorkCenterName"]))
        {
            sql.AppendFormat(" AND wc.workcentername = '{0}'", dic["WorkCenterName"]);
        }
        if (dic.ContainsKey("TeamName") && !string.IsNullOrWhiteSpace(dic["TeamName"]))
        {
            sql.AppendFormat(" AND t.teamname = '{0}'", dic["TeamName"]);
        }
        DataTable dtResource = DatabaseHelper.Query_ReturnDatTable(sql.ToString());//查询出需要统计的设备信息
        if (dtResource.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到数据！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result.DBTable = dtResource;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取设备的日历班次明细
    /// </summary>
    /// <param name="context"></param>
    private void GetResourceCalDetail(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "获取成功" };
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());//查询参数
        if (string.IsNullOrWhiteSpace(dic["startDate"]) || string.IsNullOrWhiteSpace(dic["endDate"]))
        {
            result.Result = false;
            result.Message = "请选择日期范围！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DateTime startDate = DateTime.Parse(dic["startDate"]);
        DateTime endDate = DateTime.Parse(dic["endDate"]);
        List<DayDetail> resData = new List<DayDetail>();
        while (startDate <= endDate)
        {
            resData.Add(GetWorkShiftDataByDate(dic["resourceID"], dic["workShiftID"], startDate));
            startDate = startDate.AddDays(1);
        }
        result.ReturnData = resData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取该日期的班次全部时长（小时）
    /// </summary>
    /// <param name="resourceID">设备ID</param>
    /// <param name="workShiftID">班次ID</param>
    /// <param name="dayDate">日期</param>
    /// <returns></returns>
    private DayDetail GetWorkShiftDataByDate(string resourceID, string workShiftID, DateTime dayDate)
    {
        DayDetail day = new DayDetail(dayDate);
        string sql = string.Format(@"SELECT wsd.startdate starttime,wsd.enddate endtime,wsd.mins FROM Workshift ws
                        LEFT JOIN Workshiftdetail wsd ON wsd.workshiftid = ws.workshiftid
                        WHERE ws.workshiftid = '{0}' AND ws.isuse = 0
                        UNION ALL 
                        SELECT rs.starttime,rs.endtime,NULL mins FROM resourceworkshiftdayInfo rs
                        WHERE rs.resourceid = '{1}' AND rs.daydate = to_date('{2}','yyyy-mm-dd')",
                        workShiftID, resourceID, dayDate.ToShortDateString());
        DataTable dtWorkShift = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataRow item in dtWorkShift.Rows)
        {
            if (string.IsNullOrWhiteSpace(item["mins"].ToString())) //如果为空，则计算出时长
            {
                DateTime start = DateTime.Parse(item["starttime"].ToString());
                DateTime end = DateTime.Parse(item["endtime"].ToString());
                TimeSpan ts = end - start;
                day.Hours += ts.TotalMinutes / (double)60;//累计小时
            }
            else
            {
                day.Hours += (double)int.Parse(item["mins"].ToString()) / (double)60; //累计小时
            }
            day.WSDetail.Add(new WorkShiftDetail()
            {
                WSTimeDetail = string.Format("{0}-{1}", item["starttime"].ToString(), item["endtime"].ToString()),
                starttime = item["starttime"].ToString(),
                endtime = item["endtime"].ToString()
            });//添加明细
        }
        day.Hours = Math.Round(day.Hours, 2);
        return day;
    }

    /// <summary>
    /// 获取该日期的班次明细
    /// </summary>
    /// <param name="context"></param>
    private void GetWorkShiftListByDate(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "获取成功" };
        string workShiftID = context.Request["workShiftID"].ToString();//班次ID
        string resourceID = context.Request["resourceID"].ToString();//设备ID
        string dayDate = context.Request["dayDate"].ToString(); //日期
        string sql = string.Format(@"SELECT * FROM (
                        SELECT wsd.startdate starttime,wsd.enddate endtime FROM Workshift ws
                        LEFT JOIN Workshiftdetail wsd ON wsd.workshiftid = ws.workshiftid
                        WHERE ws.workshiftid = '{0}' AND ws.isuse = 0
                        UNION ALL 
                        SELECT rs.starttime,rs.endtime FROM resourceworkshiftdayInfo rs
                        WHERE rs.resourceid = '{1}' AND rs.daydate = to_date('{2}','yyyy-mm-dd')
                        ) ORDER BY starttime", workShiftID, resourceID, dayDate);
        DataTable dtWorkShift = DatabaseHelper.Query_ReturnDatTable(sql);
        result.DBTable = dtWorkShift;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存设备日历班次数据
    /// </summary>
    /// <param name="context"></param>
    private void SaveResCalWorkShiftData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        Dictionary<string, string> pageDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (DateTime.Parse(pageDic["wsStartTime"]) >= DateTime.Parse(pageDic["wsEndTime"])) //如果开始时间大于或等于结束时间，则提示，不保存
        {
            result.Result = false; result.Message = "开始时间不能大于或等于结束时间";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        /*验证数据不能为空*/
        if (string.IsNullOrWhiteSpace(pageDic["resourceID"]) || string.IsNullOrWhiteSpace(pageDic["workShiftID"]) || string.IsNullOrWhiteSpace(pageDic["dayDate"]))
        {
            result.Result = false; result.Message = "数据有误，请刷新页面重新添加";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        /*验证数据不能重叠*/
        string sql = string.Format(@"SELECT wsd.startdate starttime,wsd.enddate endtime FROM Workshift ws
                        LEFT JOIN Workshiftdetail wsd ON wsd.workshiftid = ws.workshiftid
                        WHERE ws.workshiftid = '{0}' AND ws.isuse = 0
                        UNION ALL 
                        SELECT rs.starttime,rs.endtime FROM resourceworkshiftdayInfo rs
                        WHERE rs.resourceid = '{1}' AND rs.daydate = to_date('{2}','yyyy-mm-dd')",
                        pageDic["workShiftID"], pageDic["resourceID"], pageDic["dayDate"]);
        DataTable dtWsTime = DatabaseHelper.Query_ReturnDatTable(sql);
        DateTime wsStartTime = DateTime.Parse(pageDic["wsStartTime"]);//页面填写的开始时间
        DateTime wsEndTime = DateTime.Parse(pageDic["wsEndTime"]);//页面填写的结束时间
        foreach (DataRow item in dtWsTime.Rows)
        {
            DateTime startTime = DateTime.Parse(item["starttime"].ToString());
            DateTime endtime = DateTime.Parse(item["endtime"].ToString());
            if (wsStartTime >= startTime && wsStartTime <= endtime) //如果开始时间在该班次范围内，则重复
            {
                result.Result = false; result.Message = "时间重叠，请重新填写";
                break;
            }
            if (wsEndTime >= startTime && wsEndTime <= endtime) //如果结束时间在该班次范围内，则重复
            {
                result.Result = false; result.Message = "时间重叠，请重新填写";
                break;
            }
            if (wsStartTime <= startTime && wsEndTime >= endtime) //如果开始时间和结束时间包含该班次范围，则重复
            {
                result.Result = false; result.Message = "时间重叠，请重新填写";
                break;
            }
        }
        if (result.Result) //验证是否成功
        {
            /*保存数据*/
            StringBuilder sqlBl = new StringBuilder();
            sqlBl.Append(@"INSERT INTO resourceworkshiftdayInfo(Resourceworkshiftdayinfoid,Resourceid,Daydate,Starttime,Endtime,Createtime,Createby) VALUES(");
            sqlBl.AppendFormat("'{0}',", Guid.NewGuid().ToString());
            sqlBl.AppendFormat("'{0}',", pageDic["resourceID"]);//设备ID
            sqlBl.AppendFormat("to_date('{0}','yyyy-mm-dd'),", pageDic["dayDate"]);//日期
            sqlBl.AppendFormat("'{0}',", pageDic["wsStartTime"]);//班次开始时间
            sqlBl.AppendFormat("'{0}',", pageDic["wsEndTime"]);//班次结束时间
            sqlBl.Append("SYSDATE,");//创建时间
            sqlBl.AppendFormat("'{0}')", m_UserInfo.EmployeeID);//创建人
            DatabaseHelper.ExecuteSql(sqlBl.ToString());
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 日期班次明细
    /// </summary>
    private class DayDetail
    {
        public DayDetail(DateTime dayDate)
        {
            DayDate = dayDate.ToShortDateString();
            Hours = 0;
            WSDetail = new List<WorkShiftDetail>();
        }
        /// <summary>
        /// 日期
        /// </summary>
        public string DayDate { get; set; }
        /// <summary>
        /// 当前日期班次时长
        /// </summary>
        public double Hours { get; set; }
        /// <summary>
        /// 班次明细
        /// </summary>
        public List<WorkShiftDetail> WSDetail { get; set; }
    }

    /// <summary>
    /// 班次明细
    /// </summary>
    private class WorkShiftDetail
    {
        /// <summary>
        /// 班次时间明细
        /// </summary>
        public string WSTimeDetail { get; set; }
        /// <summary>
        /// 班次时间明细开始时间
        /// </summary>
        public string starttime { get; set; }
        /// <summary>
        /// 班次时间明细结束时间
        /// </summary>
        public string endtime { get; set; }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}